package com.dwjm.shop.order;

import com.dwjm.shop.utils.ConnectionDatabaseForMySQLUseJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ShopOrderDaoImpl implements ShopOrderDao {
    Connection connection = null;
    PreparedStatement pstmt = null;
    ResultSet rset = null;

    public ShopOrderDaoImpl() {
        connection = ConnectionDatabaseForMySQLUseJdbc.getConnection();
    }

    @Override
    public boolean createOrder(ShopOrder order) {
        try {
            String sql = "INSERT INTO t_order(gid, title, price, cid, state) VALUES(?,?,?,?,?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, order.getGid());
            pstmt.setString(2, order.getTitle());
            pstmt.setDouble(3, order.getPrice());
            pstmt.setLong(4, order.getCid());
            pstmt.setLong(5, order.getState());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources();
        }
    }

    @Override
    public boolean updateOrderState(Long orderId, String newState) {
        try {
            String sql = "UPDATE t_order SET state = ? WHERE id = ?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, newState);
            pstmt.setLong(2, orderId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            closeResources();
        }
    }

    @Override
    public List<ShopOrder> findOrdersByUserId(Long userId) {
        List<ShopOrder> orders = new ArrayList<>();
        try {
            String sql = "SELECT * FROM t_order WHERE cid = ?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, userId);
            rset = pstmt.executeQuery();

            while(rset.next()) {
                ShopOrder order = new ShopOrder(
                        rset.getLong("id"),
                        rset.getLong("gid"),
                        rset.getString("title"),
                        rset.getDouble("price"),
                        rset.getLong("cid"),
                        rset.getLong("state")
                );
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources();
        }
        return orders;
    }

    @Override
    public ShopOrder findOrderById(Long orderId) {
        try {
            String sql = "SELECT * FROM t_order WHERE id = ?";
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, orderId);
            rset = pstmt.executeQuery();

            if(rset.next()) {
                return new ShopOrder(
                        rset.getLong("id"),
                        rset.getLong("gid"),
                        rset.getString("title"),
                        rset.getDouble("price"),
                        rset.getLong("cid"),
                        rset.getLong("state")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeResources();
        }
        return null;
    }

    private void closeResources() {
        try {
            if(rset != null) rset.close();
            if(pstmt != null) pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        // 1. 初始化DAO
        ShopOrderDao orderDao = new ShopOrderDaoImpl();

        // 2. 准备测试数据
        ShopOrder testOrder = new ShopOrder(
                 null,  // id由数据库自增
                1L,
                "测试商品",
                99.99,
                2L,
                0L   // 初始状态
        );

        // 3. 测试创建订单
        System.out.println("===== 测试创建订单 =====");
        boolean createResult = orderDao.createOrder(testOrder);
        System.out.println("创建结果: " + (createResult ? "成功" : "失败"));

        // 4. 测试查询订单
        System.out.println("\n===== 测试查询订单 =====");
        List<ShopOrder> orders = orderDao.findOrdersByUserId(1L);
        System.out.println("查询到 " + orders.size() + " 条订单");
        if(!orders.isEmpty()) {
            ShopOrder firstOrder = orders.get(0);
            System.out.println("首条订单详情: ");
            System.out.println("ID: " + firstOrder.getId());
            System.out.println("商品ID: " + firstOrder.getGid());
            System.out.println("状态: " + firstOrder.getState());
        }

        // 5. 测试更新状态
        System.out.println("\n===== 测试更新状态 =====");
        if(!orders.isEmpty()) {
            Long orderId = orders.get(0).getId();
            boolean updateResult = orderDao.updateOrderState(orderId, "1");
            System.out.println("更新结果: " + (updateResult ? "成功" : "失败"));

            // 验证更新
            ShopOrder updatedOrder = orderDao.findOrderById(orderId);
            System.out.println("更新后状态: " + updatedOrder.getState());
        }
    }
}
